﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Spring.Objects.Factory.Support;
using Strongshell.Recoil.Core.Composition;

namespace Strongshell.Recoil.Core.Integration
{
    public class ContainerSelector : IContainerSelector
    {
        private readonly IObjectDefinitionRegistry objectDefinitionRegistry;

        public ContainerSelector(IObjectDefinitionRegistry objectDefinitionRegistry)
        {
            this.objectDefinitionRegistry = objectDefinitionRegistry;
        }

        public IContainerSelector With<TWiringContainer>() where TWiringContainer : WiringContainer
        {
            return With(typeof(TWiringContainer));
        }

        public IContainerSelector With(Type wiringContainerType)
        {
            var ci = wiringContainerType.GetConstructor(Type.EmptyTypes);

            var container = (WiringContainer) ci.Invoke(null);

            container.SetupContainer();

            foreach (var configuration in container.ObjectConfigurations)
            {
                objectDefinitionRegistry.RegisterObjectDefinition(configuration.Name, configuration.Builder.ObjectDefinition);

                foreach (var alias in configuration.Aliases)
                {
                    objectDefinitionRegistry.RegisterAlias(configuration.Name, alias);
                }
            }

            return this;
        }
    }
}
